package com.community.sqlapp.databaseConfiguration;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * 数据源配置类
 */
@Configuration
public class DataSourceConfig {
    @Bean
    @ConfigurationProperties("spring.datasource.db1")
    public DataSource db1DataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties("spring.datasource.db2")
    public DataSource db2DataSource() {
        return DataSourceBuilder.create().build();
    }
    @Bean
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource") // 使用默认数据源配置
    public DataSource primaryDataSource() {
        return DataSourceBuilder.create().build();
    }
    @Bean
    public DataSource dynamicDataSource(
            @Qualifier("db1DataSource") DataSource db1DataSource,
            @Qualifier("db2DataSource") DataSource db2DataSource) {

        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put("db1", db1DataSource);
        targetDataSources.put("db2", db2DataSource);

        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        dynamicDataSource.setTargetDataSources(targetDataSources);
        dynamicDataSource.setDefaultTargetDataSource(db1DataSource);

        // 重要：设置数据源查找方法
        dynamicDataSource.afterPropertiesSet();

        return dynamicDataSource;
    }
}
